import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../l10n/app_localizations.dart';

class ErcodeTextField extends StatefulWidget {
  final TextEditingController? controller;
  final ValueChanged<String>? onChanged;
  final ValueChanged<String>? onSendCode;

  const ErcodeTextField({
    super.key,
    this.controller,
    this.onChanged,
    this.onSendCode,
  });

  @override
  State<ErcodeTextField> createState() => ErcodeTextFieldState();
}

class ErcodeTextFieldState extends State<ErcodeTextField> {
  late TextEditingController _controller;
  int _countdown = 0;
  Timer? _timer;
  DateTime? _lastTapTime;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller ?? TextEditingController();
    _controller.addListener(() {
      setState(() {});
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void startCountdown() {
    _startCountdown();
  }

  void _startCountdown() {
    setState(() {
      _countdown = 60;
    });

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdown > 0) {
        setState(() {
          _countdown--;
        });
      } else {
        _timer?.cancel();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 48,
      decoration: BoxDecoration(
        border: Border.all(color: const Color(0xFFD2D2D2), width: 1),
        borderRadius: BorderRadius.circular(22),
        color: Colors.white,
      ),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _controller,
              onChanged: widget.onChanged,
              keyboardType: TextInputType.text,
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9]')),
              ],
              decoration: InputDecoration(
                contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                hintText: AppLocalizations.of(context)!.pleaseEnter + AppLocalizations.of(context)!.verificationCode,
                hintStyle: const TextStyle(color: Color(0xFFB2B2B2)),
                filled: true,
                fillColor: Colors.white,
                border: UnderlineInputBorder(
                  borderRadius: BorderRadius.circular(22),
                  borderSide: BorderSide.none,
                ),
              ),
              style: TextStyle(color: Color(0xFF222222),fontSize: isChineseLocale() ? 14 : 13),
            ),
          ),
          // const SizedBox(width: 8),
          GestureDetector(
            onTap: _countdown > 0
                ? null
                : () {
                    final now = DateTime.now();
                    if (_lastTapTime != null && now.difference(_lastTapTime!).inSeconds < 2) {
                      return;
                    }
                    _lastTapTime = now;
                    widget.onSendCode?.call(_controller.text);
                  },
            child: Container(
              width: 95,
              height: 48,
              alignment: Alignment.center,
              child: Text(
                _countdown > 0
                    ? '${_countdown}s'
                    : AppLocalizations.of(context)!.sendCode,
                style: TextStyle(
                  color: _countdown > 0 ? Color(0xFF666666) : Color(0xFF5D5FEE),
                ),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
              ),
            ),
          ),
        ],
      ),
    );
  }
}